package com.mybatisflex.admin.service.impl;

import com.mybatisflex.admin.entity.Account;
import com.mybatisflex.admin.entity.AccountSession;
import com.mybatisflex.admin.interceptor.LoginInterceptor;
import com.mybatisflex.admin.mapper.AccountMapper;
import com.mybatisflex.admin.mapper.AccountSessionMapper;
import com.mybatisflex.admin.service.AccountService;
import com.mybatisflex.admin.util.DateUtil;
import com.mybatisflex.admin.util.HashUtil;
import com.mybatisflex.admin.util.Result;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

import static com.mybatisflex.admin.entity.table.AccountTableDef.ACCOUNT;

/**
 *  服务层实现。
 *
 * @author michael
 * @since 2023-07-01
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private AccountSessionMapper accountSessionMapper;


    @Override
    public Result login(String userName, String password) {
        if (!StringUtils.hasText(userName)) {
            return Result.error(1, "用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            return Result.error(2, "密码不能为空");
        }

        Account account = accountMapper.selectOneByCondition(ACCOUNT.USER_NAME.eq(userName));
        if (account == null) {
            return Result.error(3, "账户或密码不正确");
        }

        String salt = account.getSalt();
        String encryptedPassword = HashUtil.sha256(salt + password);

        //密码错误
        if (!encryptedPassword.equals(account.getPassword())) {
            return Result.error(3, "账户或密码不正确");
        }

        AccountSession session = new AccountSession();
        session.setAccountId(account.getId());
        session.setCreated(new Date());
        session.setExpireAt(DateUtil.addDays(new Date(),2));

        accountSessionMapper.insert(session);

        return Result.success().set(LoginInterceptor.loginSessionId, session.getId()).set("accountId", account.getId());
    }
}